package com.example.niuke.controller;


import com.example.niuke.entity.DiscussPost;
import com.example.niuke.entity.Page;
import com.example.niuke.entity.User;
import com.example.niuke.service.DiscussPostService;
import com.example.niuke.service.LikeService;
import com.example.niuke.service.UserService;
import com.example.niuke.util.CommunityConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class HomeController implements CommunityConstant {
    /**
     * Auther sun
     * DATE 2022/4/14 22:07
     * VERSION 1.0
     */

    private static final Logger logger = LoggerFactory.getLogger(HomeController.class);

    @Resource
    private LikeService likeService;
    @Resource
    private UserService userService;

    @Resource
    private DiscussPostService discussPostService;

    @GetMapping("/index")
    public String getIndexPage(Model model, Page page){
        page.setRows(discussPostService.selectDiscussPostRows(0));
        page.setPath("/index");
        List<DiscussPost> list = discussPostService.findDiscussPosts(0, page.getOffset(), page.getLimit());
        ArrayList<Map<String, Object>> discussPosts = new ArrayList<>();
        if(list != null){
            for(DiscussPost post:list){
                HashMap<String, Object> map = new HashMap<>();
                map.put("post", post);
                User user = userService.findUserById(post.getUserId());
                map.put("user", user);

                long likeCount = likeService.findEntityLikeCount(ENTITY_TYPE_POST, post.getId());
                map.put("likeCount", likeCount);

                discussPosts.add(map);
            }
        }
        model.addAttribute("discussPosts",discussPosts);
        return "/index";
    }
    @GetMapping("/")
    public String index() {
        return "redirect:/index";
    }

    @GetMapping("/error")
    public String getErrorPage() {
        return "/error/500";
    }

    @GetMapping("/denied")
    public String getDeniedPage() {
        return "/error/404";
    }
}
